package com.jerry.security.controller;

import com.jerry.security.validate.ValidateCodeType;
import com.jerry.security.validate.image.ImageCode;
import com.jerry.security.validate.sms.SmsCode;
import com.jerry.security.validate.ValidateCodeGenerator;
import com.jerry.security.validate.sms.SmsCodeSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class ValidateController {

    @Autowired
    private ValidateCodeGenerator imageCodeGenerator;
    @Autowired
    private ValidateCodeGenerator smsCodeGenerator;
    @Autowired
    private SmsCodeSender smsCodeSender;

    /**
     * 图形验证码
     */
    @RequestMapping("/code/image")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 根据随机数生成图片
        ImageCode imageCode = (ImageCode) imageCodeGenerator.generate(request);
        // 将随机数存到session中
        request.getSession().setAttribute(ValidateCodeType.IMAGE.getParamNameOnValidate(),imageCode);
        // 将生成的图片写到接口响应中
        ImageIO.write(imageCode.getImage(),"JPEG", response.getOutputStream());
    }

    /**
     * 短信验证码
     */
    @RequestMapping("/code/sms")
    public void smsCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成随机数
        SmsCode smsCode = (SmsCode) smsCodeGenerator.generate(request);
        // 将随机数存到session中
        request.getSession().setAttribute(ValidateCodeType.SMS.getParamNameOnValidate(), smsCode);
        // 将生成的随机数通过短信服务商发送出去
        System.out.println("短信验证码 == "+smsCode);
        String mobile = (String)request.getParameter("mobile");
        smsCodeSender.send(mobile,smsCode.getCode());
    }

}
